package cn.itsource.basic.service.impl;

import cn.itsource.basic.exception.BusinessException;
import cn.itsource.basic.service.ILoginService;
import cn.itsource.basic.util.MD5Utils;
import cn.itsource.basic.vo.LoginVo;
import cn.itsource.user.domain.Logininfo;
import cn.itsource.user.mapper.LogininfoMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /*
    *登录流程
    * 1.参数校验
    * 2.根据username,type查询t_logininfo
    *   3.1未查到,抛异常
    *   3.2查到
    *       a.比对密码是否正确
    *       b.产生uuid随机字符串,即token
    *       c.以token为key,登录信息为value,存到redis,过期时间30min
    *       d.把token,logininfo响应给前端
    *
    * */

    @Override
    public HashMap<String, Object> account(LoginVo loginVo) {
//        1.参数校验
        if (StringUtils.isBlank(loginVo.getUsername())
            ||StringUtils.isBlank(loginVo.getPassword())
            ||StringUtils.isBlank(loginVo.getType())
        ){
            throw new BusinessException("参数不能为空");
        }
//        2.根据username,type查询t_logininfo
        Logininfo logininfo = logininfoMapper.loadByAccountAndType(loginVo.getUsername(),loginVo.getType());
//          3.1未查到,抛异常
        if (logininfo == null){
            throw new BusinessException("用户名或密码错误");
        }
//          3.2查到
//              a.比对密码是否正确
        //加密,加盐
        if (!logininfo.getPassword().equals(MD5Utils.encrypByMd5(loginVo.getPassword()) + logininfo.getSalt())){
            throw new BusinessException("用户名或密码错误");
        }
//              b.产生uuid随机字符串,即token
        String token = UUID.randomUUID().toString();
//              c.以token为key,登录信息为value,存到redis,过期时间30min
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//              d.把token,logininfo响应给前端
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        //置空敏感信息
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        map.put("logininfo",logininfo);
        return map;


    }
}
